package com.mgg.goods.controller;

import com.mgg.common.enums.ResultEnum;
import com.mgg.common.util.ResultVOUtil;
import com.mgg.goods.entity.GoodsAttrDO;
import com.mgg.goods.entity.GoodsDO;
import com.mgg.goods.entity.GoodsSpecDO;
import com.mgg.goods.enums.GoodsResultEnum;
import com.mgg.goods.service.BaseGoodsService;
import com.mgg.goods.service.goods.GoodsService;
import com.mgg.goods.vo.GoodsAttrVO;
import com.mgg.goods.vo.GoodsSimpleVO;
import com.mgg.goods.vo.GoodsSpecVO;
import com.mgg.goods.vo.GoodsVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mgg.common.util.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: lijun
 * @Date: 2018/9/10 15:46
 */
@RestController
public class GoodsController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private BaseGoodsService baseGoodsService;

    @Autowired
    private GoodsService goodsService;

    /**
     * 获取商品详情
     * @param goodsId
     * @return
     * @throws Exception
     */
    @GetMapping(path="/{id}")
    public Object findGoodsById(@PathVariable(value="id") String goodsId){
        GoodsDO goodsDO = baseGoodsService.getGoodsById(goodsId);
        if (!"1".equals(goodsDO.getStatus())) {
            return ResultVOUtil.error(GoodsResultEnum.GOODS_NOT_EXIST);
        }
        List<GoodsAttrVO> attrList = initGoodsAttrVOList(goodsDO.getAttrs());
        List<GoodsSpecVO> specList = initGoodsSpecVOList(goodsDO.getSpecs());
        GoodsVO goodsVO = new GoodsVO();
        BeanUtils.copyProperties(goodsDO,goodsVO);
        goodsVO.setAttrs(attrList);
        goodsVO.setSpecs(specList);
        long invQty = 0;
        long salesQty = 0;
        for (GoodsSpecVO specVO : specList) {
            invQty += specVO.getInvQty();
            salesQty += specVO.getSalesQty();
        }
        goodsVO.setInvQty(invQty);
        goodsVO.setSalesQty(salesQty);
        goodsVO.setSupplierId(goodsDO.getSpecs().get(0).getSupplierId());

        //判断是不是秒杀商品
        if ("1".equals(goodsVO.getGoodsType())) {
            List<String> statusList = goodsService.listSeckillGoodsStatus(goodsId);
            if (statusList.contains("1")) {
                goodsVO.setStatus("1");
            } else if (statusList.contains("0")){
                goodsVO.setStatus("0");
            } else {
                goodsVO.setStatus("2");
            }
        }
        return ResultVOUtil.success(goodsVO);
    }

    /**
     *  初始化商品销售规格
     * @param specs
     * @return
     */
    private List<GoodsSpecVO> initGoodsSpecVOList(List<GoodsSpecDO> specs) {
        List<GoodsSpecVO> specList = new ArrayList<>();
        for (GoodsSpecDO specDO : specs) {
            if (1 == specDO.getStatus()) {
                GoodsSpecVO specVO = new GoodsSpecVO();
                specVO.setSpecId(specDO.getSpecId());
                specVO.setSpecName(specDO.getSpecName());
                specVO.setSpecPicture(specDO.getSpecPicture());
                specVO.setSpecPrice(specDO.getSpecPrice().doubleValue());
                Long invQty = specDO.getSellQty() + specDO.getVirtualQty();
                specVO.setInvQty(invQty < 0 ? 0 : invQty);
                specVO.setSalesQty(specDO.getSalesQty());
                specList.add(specVO);
            }
        }
        return specList;
    }

    /**
     * 初始化商品销售属性
     * @param attrs
     * @return
     */
    private List<GoodsAttrVO> initGoodsAttrVOList(List<GoodsAttrDO> attrs) {
        List<GoodsAttrVO> attrList = new ArrayList<>();
        for (GoodsAttrDO attrDO : attrs) {
            if ("1".equals(attrDO.getStatus())) {
                GoodsAttrVO attrVO = new GoodsAttrVO();
                attrVO.setAttrId(attrDO.getAttrId());
                attrVO.setAttrName(attrDO.getAttrName());
                if (attrDO.getItems() != null) {
                    attrVO.setItems(initGoodsAttrVOList(attrDO.getItems()));
                }
                attrList.add(attrVO);
            }
        }
        return attrList;
    }

    /**
     * 根据类别获取商品列表
     * @param categoryId
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping(path="/list/category")
    public Object findGoodsListByCategoryId(@RequestParam(value="catgId",required=true) String categoryId,
                                            @RequestParam(value="sort",required=false) String sort,
                                            @PageableDefault(page = 1, size = 10) Pageable page){
        List<GoodsDO> goodsDOList = baseGoodsService.listGoodsByCategoryId(categoryId, sort,"1", page);
        List<GoodsSimpleVO> goodsList = initGoodsProperty(goodsDOList);
        return ResultVOUtil.success(goodsList);
    }

    /**
     * 根据第一品类获取爆款商品列表
     * @param categoryId
     * @return
     * @throws Exception
     */
    @GetMapping(path="/list/category/first/hot")
    public Object findHotGoodsListByFirstCategoryId(@RequestParam(value="catgId",required=true) String categoryId, @RequestParam(value="sort",required=false) String sort) {
        List<GoodsDO> goodsDOList = baseGoodsService.listHotGoodsByFirstCategoryId(categoryId, sort,"1");
        List<GoodsSimpleVO> goodsList = initGoodsProperty(goodsDOList);
        return ResultVOUtil.success(goodsList);
    }

    /**
     * 根据第一品类获取商品列表
     * @param categoryId
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping(path="/list/category/first")
    public Object findGoodsListByFirstCategoryId(@RequestParam(value="catgId",required=true) String categoryId, @RequestParam String sort, @PageableDefault(page = 1, size = 10) Pageable page) {
        List<GoodsDO> goodsDOList = baseGoodsService.listGoodsByFirstCategoryId(categoryId, sort, "1", page);
        List<GoodsSimpleVO> goodsList = initGoodsProperty(goodsDOList);
        return ResultVOUtil.success(goodsList);
    }

    /**
     *
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping(path="/list/plate")
    public Object findGoodsListByPlate(@RequestParam String plateId,
                                       @RequestParam(value="is_rand",required=false) String is_rand,
                                       @RequestParam(value="sort",required=false) String sort,
                                       @PageableDefault(page = 1, size = 20) Pageable page) {
        List<GoodsDO> goodsDOList = baseGoodsService.listGoodsByPlateId(plateId, is_rand, sort, "1", page);
        List<GoodsSimpleVO> goodsList = initGoodsProperty(goodsDOList);
        return ResultVOUtil.success(goodsList);
    }

    /**
     * 商品查询
     * @param name
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/query")
    public Object queryGoods(@RequestParam(value="name",required=true) String name,
                             @RequestParam(value="sort",required=false) String sort,
                             @PageableDefault(page = 1, size = 10) Pageable page) {
        List<GoodsDO> goodsDOList = baseGoodsService.listGoodsByName(name, sort, "1", "0", page);
        List<GoodsSimpleVO> goodsList = initGoodsProperty(goodsDOList);
        goodsService.saveQueryGoodsWords(name);
        return ResultVOUtil.success(goodsList);
    }

    /**
     * 商品查询热搜词
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/query/words/hot/list")
    public Object getGoodsSearchWordHotList() {
        List<String> list = goodsService.listGoodsSearchWordHot();
        return ResultVOUtil.success(list);
    }

    /**
     * 获取推荐商品列表
     * @return
     * @throws Exception
     */
    @GetMapping(path="/list/recd")
    public Object getRecommendGoodsList() {
        List<Map<String,String>> list = goodsService.listRecommendGoods();
        return ResultVOUtil.success(list);
    }

    /**
     * 今日上新广告图,新品首发
     * @return
     * @throws Exception
     */
    @GetMapping(path="/new/starting")
    public Object getStartingGoodsList(@RequestParam(value="sort",required=false) String sort) {
        List<GoodsDO> goodsDOList = baseGoodsService.listGoodsByPlateType(21, sort,"1", null);
        List<GoodsSimpleVO>  goodsList = initGoodsProperty(goodsDOList);
        Map<String,Object> result = new HashMap<>();
        result.put("adimage", goodsService.getAdPicture(21));
        result.put("goodsList", goodsList);
        return ResultVOUtil.success(result);
    }

    /**
     * 新品爆款
     * @return
     * @throws Exception
     */
    @GetMapping(path="/new/bursting")
    public Object getBurstingGoodsList(@RequestParam(value="sort",required=false) String sort) {
        List<GoodsDO> goodsDOList = baseGoodsService.listGoodsByPlateType(22, sort,"1", null);
        List<GoodsSimpleVO> goodsList = initGoodsProperty(goodsDOList);
        return ResultVOUtil.success(goodsList);
    }

    /**
     * 新品排行
     * @return
     * @throws Exception
     */
    @GetMapping(path="/new/rankings")
    public Object getRankingsGoodsList(@RequestParam(value="sort",required=false) String sort,
                                       @PageableDefault(page = 1, size = 10) Pageable page) throws Exception {
        List<GoodsSimpleVO> goodsList = goodsService.listRankingsGoods(page);
        if(goodsList == null) {
            List<GoodsDO> goodsDOList = baseGoodsService.listGoodsByPlateType(23, sort,"1", page);
            goodsList = initGoodsProperty(goodsDOList);
        } else {
            for (GoodsSimpleVO goods : goodsList) {
                String sharePic = goods.getMainPic().split(",")[0];
                goods.setSharePic(sharePic);
                goodsService.setGoodsQty(goods);
            }
        }
        return ResultVOUtil.success(goodsList);
    }

    /**
     * 新品预告
     * @return
     * @throws Exception
     */
    @GetMapping(path="/new/preview")
    public Object getPreviewGoodsList(@RequestParam(value="sort",required=false) String sort) throws Exception {
        List<GoodsDO> goodsDOList = baseGoodsService.listGoodsByPlateType(24, sort,"1", null);
        List<GoodsSimpleVO> goodsList = initGoodsProperty(goodsDOList);
        return ResultVOUtil.success(goodsList);
    }

    private List<GoodsSimpleVO> initGoodsProperty(List<GoodsDO> goodsDOList) {
        List<GoodsSimpleVO> goodsList = new ArrayList<>(goodsDOList.size());
        for (GoodsDO goodsDO : goodsDOList) {
            GoodsSimpleVO goodsSimpleVO = new GoodsSimpleVO();
            BeanUtils.copyProperties(goodsDO,goodsSimpleVO);
            String mainPic = goodsDO.getMainPic();
            if(StringUtils.isNotEmpty(mainPic)) {
                String sharePic = mainPic.split(",")[0];
                goodsSimpleVO.setSharePic(sharePic);
            }
            goodsService.setGoodsQty(goodsSimpleVO);
            goodsList.add(goodsSimpleVO);
        }
        return goodsList;
    }
}
